package com.example.movie.ui.user

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.SimpleAdapter
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import com.bumptech.glide.Glide
import com.example.movie.R
import com.example.movie.common.constants.AppConstants
import com.example.movie.common.constants.Constants
import com.example.movie.common.constants.RequestCode
import com.example.movie.data.user.login.factory.LoginViewModelFactory
import com.example.movie.data.user.login.model.SharedLoginViewModel
import com.example.movie.ui.user.auth.LoginActivity
import com.example.movie.ui.user.order.OrderActivity
import com.example.movie.ui.user.setting.SettingActivity
import kotlinx.android.synthetic.main.fragment_user.*


class UserFragment : Fragment() {

    private val loginViewModel: SharedLoginViewModel by activityViewModels(factoryProducer = { LoginViewModelFactory() })

    private val tittles: Array<String> = arrayOf("订单", "优惠卷")

    private val images: Array<Int> =
        arrayOf(R.drawable.order, R.drawable.user_coupon)

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        loadUserData()
        return inflater.inflate(R.layout.fragment_user, container, false)
    }

    /**
     * 加载本地或者远程用户的数据
     */
    @SuppressLint("SetTextI18n")
    private fun loadUserData() {
        loginViewModel.loginResult.observe(viewLifecycleOwner, { it ->
            if (it == null){
                username.text = "请登录"
                wantSee.text = "想看 -"
                haveSeen.text = "看过 -"
                movie_portrait.setImageResource(R.mipmap.logo)
                return@observe
            }

            it.success?.let {
                with(it) {
                    username.text = nickName
                    wantSee.text = "想看 $hopeLook"
                    haveSeen.text = "看过 $hasSee"
                    Glide
                        .with(requireContext())
                        .load(AppConstants.STATIC_SOURCE_URL + headImg)
                        .placeholder(R.mipmap.logo)
                        .error(R.mipmap.ic_launcher)
                        .into(movie_portrait)
                }
                return@observe
            }

        })
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        //滚动到顶部
        scrollView.post {
            scrollView.scrollTo(0, setting.top);
        }

        setting.setOnClickListener {
            startActivity(Intent(requireActivity(), SettingActivity::class.java))
        }

        username.setOnClickListener {
            if (loginViewModel.isLoggedIn()) {
                startActivity(Intent(requireActivity(), PersonPageActivity::class.java))
            } else {
              toLogin()
            }
        }

        user_page.setOnClickListener {
            if (loginViewModel.isLoggedIn()) {
                startActivity(Intent(requireActivity(), PersonPageActivity::class.java))
            } else {
                toLogin()
            }
        }

        wantSee.setOnClickListener {
            if (loginViewModel.isLoggedIn()) {
                with(Bundle()) {
                    putInt(AppConstants.SELECT_TAB, Constants.UserInfo.HOPE_LOOK_LIST)
                    startPersonPageActivity(this)
                }
            } else {
                toLogin()
            }
        }

        haveSeen.setOnClickListener {
            if (loginViewModel.isLoggedIn()) {
                with(Bundle()) {
                    putInt(AppConstants.SELECT_TAB, Constants.UserInfo.HAVE_SEEN_LIST)
                    startPersonPageActivity(this)
                }
            } else {
                toLogin()
            }
        }

        val mutableList = mutableListOf<Map<String, Any>>()
        for (i in images.indices) {
            mutableList.add(mapOf(Pair("image", images[i]), Pair("title", tittles[i])))
        }

        user_options.adapter = SimpleAdapter(
            context, mutableList, R.layout.item_user_function, arrayOf("image", "title"),
            intArrayOf(R.id.list_item_img, R.id.activity_title)
        )

        user_options.setOnItemClickListener { _, _, position, _ ->
            when (position) {
                0 -> {
                    if (loginViewModel.isLoggedIn()) {
                        startActivity(Intent(requireContext(), OrderActivity::class.java))
                    } else {
                        startActivityForResult(
                            Intent(requireActivity(), LoginActivity::class.java),
                            RequestCode.NEED_LOGIN
                        )
                    }
                }
            }
        }
    }

    private fun toLogin() {
        startActivityForResult(
            Intent(requireActivity(), LoginActivity::class.java),
            RequestCode.NEED_LOGIN
        )
    }

    private fun startPersonPageActivity(bundle: Bundle) {
        val intent = Intent(requireActivity(), PersonPageActivity::class.java)
        intent.putExtras(bundle)
        startActivity(intent)
    }


}